package io.yuanqi.hgtcshop.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import io.yuanqi.hgtcshop.config.RedisService;
import io.yuanqi.hgtcshop.entity.dos.GoodsSku;
import io.yuanqi.hgtcshop.entity.dos.Trade;
import io.yuanqi.hgtcshop.entity.dto.TradeDTO;
import io.yuanqi.hgtcshop.entity.enums.CartTypeEnum;
import io.yuanqi.hgtcshop.entity.vo.TradeParams;
import io.yuanqi.hgtcshop.service.CartService;
import io.yuanqi.hgtcshop.service.GoodsSkuService;
import io.yuanqi.hgtcshop.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车业务层实现
 *
 * @author Chopper
 * @since 2020-03-23 12:29 下午
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OrderService orderService;


    static String errorMessage = "购物车异常，请稍后重试";

    @Override
    public TradeDTO getCheckedTradeDTO(CartTypeEnum way) {
        return null;
    }

    @Override
    public TradeDTO getAllTradeDTO() {
        return null;
    }

    @Override
    public void add(String skuId, Integer num, String openId, Boolean cover) {
        String value = redisService.getValue("CART_" + openId);
        List<GoodsSku> goodsSkus = null;
        if (value == null || !StringUtils.hasText(value) || value.contains("null")) {
            goodsSkus = new ArrayList<>();
        } else {
            goodsSkus = JSON.parseObject(value, new TypeReference<List<GoodsSku>>() {
            });
        }

        List<String> idSkuIds = new ArrayList<>();

        for (GoodsSku goodsSku : goodsSkus) {
            String id = goodsSku.getId();
            idSkuIds.add(id);
        }

        if (idSkuIds.contains(skuId)) {
            // 每件商品只能买一个
            return;
        }
        GoodsSku skuBySkuId = goodsSkuService.getSkuBySkuId(skuId);
        if (skuBySkuId != null) {
            goodsSkus.add(skuBySkuId);
        }
        redisService.setKeyValue("CART_" + openId, JSON.toJSONString(goodsSkus));

    }

    @Override
    public void delete(String[] skuIds, String openId) {
        String value = redisService.getValue("CART_" + openId);
        List<GoodsSku> goodsSkus = null;
        if (value == null || !StringUtils.hasText(value) || value.contains("null")) {
            goodsSkus = new ArrayList<>();
        } else {
            goodsSkus = JSON.parseObject(value, new TypeReference<List<GoodsSku>>() {
            });
        }

        List<String> skuIdsParamList = Arrays.asList(skuIds);

        Iterator<GoodsSku> iterator = goodsSkus.iterator();
        while (iterator.hasNext()) {
            GoodsSku next = iterator.next();
            if (null == next) continue;
            if (skuIdsParamList.contains(next.getId())) {
                iterator.remove();
            }
        }
        redisService.setKeyValue("CART_" + openId, JSON.toJSONString(goodsSkus));
    }

    @Override
    public void clean(String openId) {
        redisService.deleteKey("CART_" + openId);
    }

    @Override
    public void shippingAddress(String shippingAddressId, String way) {

    }

    @Override
    public Long getCartNum(Boolean checked) {
        return null;
    }

    @Override
    public Trade createTrade(TradeParams tradeParams) {
        return null;
    }

    @Override
    public List<GoodsSku> cartAll(String openId) {
        String value = redisService.getValue("CART_" + openId);
        List<GoodsSku> goodsSkus = JSON.parseObject(value, new TypeReference<List<GoodsSku>>() {
        });
        return goodsSkus;
    }

    @Override
    public Object createTrade(String openId, String[] skuIds, String addressId, BigDecimal totalPrice) {

        return null;
    }

    /**
     * 获取购物车类型
     *
     * @param way
     * @return
     */
    private CartTypeEnum getCartType(String way) {
        //默认购物车
        CartTypeEnum cartTypeEnum = CartTypeEnum.CART;
        if (CharSequenceUtil.isNotEmpty(way)) {
            try {
                cartTypeEnum = CartTypeEnum.valueOf(way);
            } catch (IllegalArgumentException e) {
                log.error("获取购物车类型出现错误：", e);
            }
        }
        return cartTypeEnum;
    }

    /**
     * 校验商品有效性，判定失效和库存，促销活动价格
     *
     * @param skuId 商品skuId
     */
    private GoodsSku checkGoods(String skuId) {
        return null;
    }

}
